<template>
  <div class="container">
    <el-button type="primary" size="mini" @click="drawCircle()"
      >绘制圆形</el-button
    >
    <button type="primary" size="mini" @click="drawSquare()">绘制矩形</button>
    <button type="primary" size="mini" @click="drawPolygon()">
      绘制多边形
    </button>
    <button type="primary" size="mini" @click="drawPoint()">绘制点</button>
    <button type="primary" size="mini" @click="positionIcon()">设置</button>
    <br />
    <button type="primary" size="mini" @click="editCircle()">回显圆形</button>
    <button type="primary" size="mini" @click="editSquare()">回显矩形</button>
    <button type="primary" size="mini" @click="editPolygon()">回显边形</button>
    <button type="primary" size="mini" @click="editPoint()">回显点</button>
    <div id="vue-openlayers"></div>
    <div id="coordinateInfo"></div>
    <div id="popup" class="ol-popup" style="display: none">
      <h4>保存地址</h4>
      名字:<el-input type="text" v-model="params.name" /><br />
      密码:<el-input type="password" v-model="params.password" /><br />
      <el-button @click="drawSubmit()">提交</el-button>
      <button @click="closePupop()">取消</button>
      <!-- <a  id="popup-closer" class="ol-popup-closer"></a> -->
      <div id="popup-content"></div>
    </div>
  </div>
</template>
<script src="https://unpkg.com/vue@2/dist/vue.js"></script>
  <!-- import JavaScript -->
  <script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script>
import "ol/ol.css";
import { Map, View, Overlay } from "ol";
import Tile from "ol/layer/Tile";
import OSM from "ol/source/OSM";
import LayerVector from "ol/layer/Vector";
import SourceVector from "ol/source/Vector";
import Fill from "ol/style/Fill";
import Text from "ol/style/Text";
import Style from "ol/style/Style";
import Stroke from "ol/style/Stroke";
import { Circle as CircleStyle } from "ol/style";
import Draw, { createBox } from "ol/interaction/Draw";
import { Point, Circle, LineString } from "ol/geom";
import { getCenter } from "ol/extent";
import Feature from "ol/Feature";

export default {
  data() {
    return {
      params: {},
      map: null, // 地图
      draw: null,
      source: new SourceVector({ wrapX: false }), //绘制矩形的source
      pointSource: new SourceVector({ wrapX: false }), //绘制点的source
      pointLayerList: [],
      polygonPoints: [], //多边形线条
      drawType: false,
      chartType: 0,
      circleObject: { center: [], radius: null },
      squareObject: { center: [] },
      polyGonObject: { center: [] },
      overLayPopup: null,
    };
  },
  methods: {
    initMap() {
      let raster = new Tile({
        source: new OSM({
          url: "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}",
        }),
      });

      let vector = new LayerVector({
        source: this.source,
      });
      this.map = new Map({
        target: "vue-openlayers",
        layers: [raster, vector],
        view: new View({
          projection: "EPSG:4326",
          center: [113.1206, 23.034996],
          zoom: 10,
        }),
      });
    },
    //清除所有点
    clearPointLayerList() {
      let pointLayerList = this.pointLayerList;
      for (var i = 0; i < pointLayerList.length; i++) {
        this.map.removeLayer(pointLayerList[i]);
      }
    },

    //绘制点
    drawPoint() {
      this.source.clear();
      //关闭弹框
      this.closePupop();
      //清除所有点
      this.clearPointLayerList();
      let _this = this;
      this.type = "drawPoint";
      // 绑定点击事件
      _this.drawType = true;

      this.map.on("click", function (e) {
        _this.handleClick(e, 1, _this.drawType);
      });
    },
    drawCircle() {
      // 清除资源,只留一个图形
      this.source.clear();
      //关闭弹框
      this.closePupop();
      //清除所有点
      this.clearPointLayerList();
      if (this.draw !== null) {
        this.map.removeInteraction(this.draw);
      }

      this.draw = new Draw({
        source: this.source,
        type: "Circle",
      });
      this.map.addInteraction(this.draw);
      this.draw.on("drawend", (e) => {
        let feature = e.feature;
        //获得这个圆对象
        let circle = feature.getGeometry();
        //圆中心坐标
        let center = circle.getCenter();
        this.circleObject.center = center;
        //圆的半径
        let radius = circle.getRadius();
        this.circleObject.radius = radius;
        console.log(center, radius);

        this.map.removeInteraction(this.draw);
      });
      this.drawType = false;
      this.chartType = 1;
    },
    drawSquare() {
      // 清除资源,只留一个图形
      this.source.clear();
      //关闭弹框
      this.closePupop();
      //清除所有点
      this.clearPointLayerList();
      // 停止上一次的绘制，没有此代码会出现重叠
      if (this.draw !== null) {
        this.map.removeInteraction(this.draw);
      }

      let type = "Circle";
      let geometryFunction = createBox();

      this.draw = new Draw({
        source: this.source,
        type,
        geometryFunction,
      });
      this.map.addInteraction(this.draw);
      this.draw.on("drawend", (e) => {
        let feature = e.feature;
        let square = feature.getGeometry();
        // let i2 = JSON.stringify(square.getCoordinates()[0]);
        let center = new getCenter(square.getExtent());
        this.squareObject.center = center;
        console.log(center, square.getCoordinates()[0]);
        this.map.removeInteraction(this.draw);
      });
      this.drawType = false;
      this.chartType = 2;
    },
    drawPolygon() {
      // 清除资源,只留一个图形
      this.source.clear();
      //关闭弹框
      this.closePupop();
      //清除所有点
      this.clearPointLayerList();
      if (this.draw !== null) {
        this.map.removeInteraction(this.draw);
      }
      this.draw = new Draw({
        source: this.source,
        type: "Polygon",
      });
      this.map.addInteraction(this.draw);
      this.draw.on("drawend", (e) => {
        let feature = e.feature;
        let polygon = feature.getGeometry();

        let coordinate = polygon.getCoordinates();
        let center = coordinate[0][0];
        this.polyGonObject.center = center;
        this.map.removeInteraction(this.draw);
      });
      this.drawType = false;
      this.chartType = 3;
    },
    editPoint() {
      //清除所有点
      this.clearPointLayerList();
      this.source.clear();
      let pointList = [
        [112.95800235213191, 22.94023889372843],
        [113.2425482254237, 22.94023889372843],
        [113.2425482254237, 23.127006450898673],
        [112.95800235213191, 23.127006450898673],
        [112.95800235213191, 22.94023889372893],
      ];

      for (var i = 0; i < pointList.length; i++) {
        let pointFeature = new Feature({
          geometry: new Point(pointList[i]),
        });
        this.source.addFeature(pointFeature);
        let pointLayer = new LayerVector({
          source: this.source,
          style: new Style({
            image: new CircleStyle({
              radius: 9, // 圆的半径
              fill: new Fill({ color: "red" }), // 填充颜色
            }),
            text: new Text({
              // 字体与大小
              text: "张三",
              offsetY: 15,
              offsetX: 0,
              fill: new Fill({ color: "red" }), // 填充颜色
            }),
          }),
        });
        this.pointLayerList.push(pointLayer);
        this.map.addLayer(pointLayer);
      }
    },
    //回显圆形
    editCircle() {
      //清除所有点
      this.clearPointLayerList();
      this.source.clear();
      let drawFeature = new Feature({
        geometry: new Circle(
          [113.07775334545822, 23.06768032512414],
          0.14458610404260241
        ),
      });
      this.source.addFeature(drawFeature);
      this.circleObject.center = [113.07775334545822, 23.06768032512414]
      this.chartType = 1
      this.positionIcon(true)
    },
    //回显矩形
    editSquare() {
      //清除所有点
      this.clearPointLayerList();
      this.source.clear();
      let polygonFeature = new Feature({
        geometry: new LineString([
          [112.95800235213191, 22.94023889372843],
          [113.2425482254237, 22.94023889372843],
          [113.2425482254237, 23.127006450898673],
          [112.95800235213191, 23.127006450898673],
          [112.95800235213191, 22.94023889372843],
        ]),
      });
      this.source.addFeature(polygonFeature);
      this.squareObject.center = [112.95800235213191, 22.94023889372843]
      this.chartType = 2
      this.positionIcon(true)
    },
    //回显多边形
    editPolygon() {
      //清除所有点
      this.clearPointLayerList();
      this.source.clear();
      let polygonFeature = new Feature({
        geometry: new LineString([
          [112.95800235213191, 22.94023889372843],
          [113.2425482254237, 22.94023889372843],
          [113.2425482254237, 23.127006450898673],
          [112.95800235213191, 23.127006450898673],
          [112.95800235213191, 22.94023889372843],
        ]),
      });
      this.source.addFeature(polygonFeature);
      this.polyGonObject.center = [112.95800235213191, 22.94023889372843]
      this.chartType = 3
      this.positionIcon(true)
    },
    //显示弹框
    positionIcon(isEdit) {
     if(this.draw === null){
        if(isEdit !== true){
          alert('请绘制图形')
          return
        }
     }
      var content = document.getElementById("popup");
      content.style.display = "block";
      var popup = new Overlay({
        element: content, // 将弹框挂载在 dom 上
        autoPan: true, // 如果弹框显示不全则自动归位
        positioning: "bottom-center", // 相对于其位置属性的实际位置
        stopEvent: true, // 事件冒泡
        autoPanAnimation: {
          duration: 250, // 地图移动速度
        },
      });
      var chartType = this.chartType;
      var coodinate = [];
      if (chartType === 1) {
        coodinate = this.circleObject.center;
      } else if (chartType === 2) {
        coodinate = this.squareObject.center;
      } else if (chartType === 3) {
        coodinate = this.polyGonObject.center;
      }
      
      console.log(chartType,coodinate)
      popup.setPosition(coodinate);
      this.map.addOverlay(popup);
      this.overLayPopup = popup;
    },
    handleClick(e, type, drawType) {
      let point = e.coordinate;
      if (type === 1 && drawType === true) {
        //绘制点
        // 创建Feature 设置点的位置
        const pointFeature = new Feature({
          geometry: new Point(point),
        });
        this.source.addFeature(pointFeature);
        let pointLayer = new LayerVector({
          source: this.source,
          style: new Style({
            image: new CircleStyle({
              radius: 9, // 圆的半径
              fill: new Fill({ color: "red" }), // 填充颜色
            }),
            text: new Text({
              // 字体与大小
              text: "张三",
              offsetY: 15,
              offsetX: 0,
              fill: new Fill({ color: "red" }), // 填充颜色
            }),
          }),
        });
        
        this.pointLayerList.push(pointLayer);
        // 最后别忘了把图层加到地图上
        this.map.addLayer(pointLayer);
      } else if (type === 2) {
        let features = [];
        this.polygonPoints.push(point);

        var polygon = new Polygon([this.polygonPoints]);
        var feature = new Feature(polygon);
        features.push(feature);
        var vectorSource = new SourceVector();
        vectorSource.addFeatures(features);
        const styleFunction = function () {
          return new Style({
            fill: new Fill({
              color: [255, 255, 255, 0.33],
            }),
            stroke: new Stroke({
              width: 2,
              color: "#dc5246",
            }),
          });
        };
        var vlayer = new LayerVector({
          title: "polygon",
          source: vectorSource,
          style: styleFunction,
        });
        this.map.addLayer(vlayer);
      } else {
        return;
      }
    },
    //弹窗内容提交
    drawSubmit() {
      alert("保存成功");
      // 清除资源,只留一个图形
      this.source.clear();
      //关闭弹框
      this.closePupop();
      //清除所有点
      this.clearPointLayerList();
      // 停止上一次的绘制，没有此代码会出现重叠
      if (this.draw !== null) {
        this.map.removeInteraction(this.draw);
      }
    },
    //弹窗关闭
    closePupop() {
      this.params = {};
      if (this.overLayPopup !== null) {
        this.overLayPopup.setPosition(undefined);
        this.overLayPopup = null;
      }
    },
  },
  mounted() {
    this.initMap();
  },
};
</script>
<style scoped>
.container {
  width: 1000px;
  height: 60000x;
  border: 1px solid #42b983;
}

#vue-openlayers {
  width: 900px;
  height: 500px;
  border: 1px solid #42b983;
  position: relative;
}

.ol-popup {
  position: absolute;
  background-color: white;
  -webkit-filter: drop-shadow(0 1px 4px rgba(0, 0, 0, 0.2));
  filter: drop-shadow(0 1px 4px #ffc125);
  padding: 15px;
  border-radius: 10px;
  border: 1px solid #cccccc;
  bottom: 12px;
  left: -50px;
  min-width: 200px;
}

.ol-popup:after,
.ol-popup:before {
  top: 100%;
  border: solid transparent;
  content: " ";
  height: 0;
  width: 0;
  position: absolute;
  pointer-events: none;
}

.ol-popup:after {
  border-top-color: white;
  border-width: 10px;
  left: 48px;
  margin-left: -10px;
}

.ol-popup:before {
  border-top-color: #cccccc;
  border-width: 11px;
  left: 48px;
  margin-left: -11px;
}

.ol-popup-closer {
  text-decoration: none;
  position: absolute;
  top: 2px;
  right: 8px;
  color: red;
}

.ol-popup-closer:after {
  content: "✖";
}
</style>